<template>
  <div class="header">
    <div class="header-left">
      <img class="logo" src="@/assets/images/header/logo.png" alt="logo" />
      <span class="logo-text">三维底座可视化</span>
      <div class="statistics" @click="handleStatistics">
        <div class="statistics-item">
          <span class="statistics-item-title">井下人员：</span>
          <span class="statistics-item-value">{{ statistics.total }}</span>
        </div>
        <div class="statistics-item">
          <span class="statistics-item-title">带班领导人数：</span>
          <span class="statistics-item-value">{{ statistics.leaderCount }}</span>
        </div>
      </div>
    </div>
    <div class="header-right">
      <toogle-model class="toogle-model" v-model:model="model" :model-list="modelList" @click="toogleModelFun" />

      <el-select class="area-select" v-model="area" value-key="id" filterable placeholder="请选择区域" size="large" clearable
        @change="handleAreaChange">
        <el-option v-for="item in areaList" multiple :key="item.id" :label="item.label" :value="item" />
      </el-select>

      <el-divider direction="vertical" />
      <transition name="el-zoom-in-top">
        <div class="menu-box" v-show="model === 'realtime'">
          <template v-for="item in menuList" :key="item.value">
            <div class="menu-item" :class="{ active: modeParams.menu === item.value }" @click="handleClick(item.value)">
              <span>{{ item.label }}</span>
            </div>
          </template>
        </div>
      </transition>

      <el-badge v-show="model === 'realtime'" :value="alarmCount" :hidden="alarmCount === 0" :max="99" class="badge"
        @click="handleAlarm">
        <i class="iconfont icon-yujingbaojing" :class="{ danger: alarmCount > 0 }" />
      </el-badge>

      <el-button class="login-btn" type="primary" round>
        <span @click="handleLogout">退出</span>
      </el-button>
    </div>

    <el-dialog title="请选择要回溯时间段" append-to-body v-model="showDateRange" width="500px" :modal="false"
      @close="closeDialog">
      <el-date-picker class="datePicker" :disabled-date="disabledDateFun" v-model="dateRange" size="large"
        start-placeholder="回溯开始时间" end-placeholder="回溯结束时间" format="YYYY-MM-DD HH:mm" value-format="YYYY-MM-DD HH:mm"
        type="datetimerange" />
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancelRecall">取消回溯</el-button>
          <el-button type="primary" @click="confirmRecall"> 确定回溯 </el-button>
        </div>
      </template>
    </el-dialog>

    <audio class="audioRef" :src="BASE_URL + 'alarm.mp3'" loop ref="audioRef"></audio>
  </div>
</template>

<script setup lang="ts">
import ToogleModel from '@/components/toogle-model.vue'
import { ref, onMounted, onUnmounted, watch } from 'vue'
import emiter from '@/utils/mitt'
import { getPersonCount } from '@/api/person'
import Statistics from './statistics.vue'
import { $bDialog } from '@/components/b-dialog'
import AlarmTable from '@/views/DataView/alarm/alarmTable.vue'
import { useAlarmStore } from '@/store/alarm'
import { useAuthStore } from '@/store/auth'
import { dictStore } from '@/store/dict'
import { storeToRefs } from 'pinia'
import { getTunnelIdByAreaId } from '@/api/road'
import { createSSE } from '@/api/sse'
import { usePersonStore } from '@/store/person'
import { useActiveObject } from '@/store/activeObject'
const BASE_URL = import.meta.env.BASE_URL
// 菜单
const menuList = ref([
  { label: '区域信息', value: '0' },
  { label: '人员信息', value: '1' },
  { label: '视频监控', value: '2' },
  { label: '传感器信息', value: '3' },
  { label: '报警信息', value: '4' }
])

const handleClick = (value: string) => {
  authStore.setModeParamsItem('menu', value)
}
// 模式切换
const model = ref('realtime')
const modelList = ref([
  { label: '实时模式', value: 'realtime' },
  { label: '回溯模式', value: 'backtracking' }
])

const { setActiveFilter } = useActiveObject()

const dateRange = ref([])
const showDateRange = ref(false)
function toogleModelFun (value: string) {
  if (value === 'backtracking') {
    showDateRange.value = true
    return
  } else {
    authStore.setModeParamsItem('model', 'realtime')
  }
}

function closeDialog () {
  if (dateRange.value[0] && dateRange.value[1]) {
    showDateRange.value = false
    return
  }
  model.value = 'realtime'
}

function cancelRecall () {
  showDateRange.value = false
  dateRange.value = []
  authStore.setGlobalParamsItem('startTime', '')
  authStore.setGlobalParamsItem('endTime', '')
}

const authStore = useAuthStore()
function confirmRecall () {
  showDateRange.value = false
  if (dateRange.value[0] && dateRange.value[1]) {
    authStore.setGlobalParamsItem('startTime', dateRange.value[0])
    authStore.setGlobalParamsItem('endTime', dateRange.value[1])
    authStore.setModeParamsItem('model', 'backtracking')
  }
}

function disabledDateFun (time: Date) {
  return time.getTime() > Date.now()
}
// 人员统计
const statistics = ref({
  total: 0,
  leaderCount: 0
})
const handleStatistics = () => {
  $bDialog({
    title: '近24小时井下人员变化',
    Comp: Statistics,
    width: 600,
    height: 300
  })
}

const { globalParams, modeParams } = storeToRefs(authStore)

const countInterval = ref()
watch(() => modeParams.value.model, (val) => {
  $bDialog.closeAll()
  setTimeout(async () => {
    const { data } = await getPersonCount()
    statistics.value = data
  })
  setActiveFilter(['workArea'])
  clearInterval(countInterval.value)
  authStore.setSceneTypeList([])
  if (val === 'backtracking') {
    model.value = 'backtracking'
    if (globalParams.value.areaId) {
      setActiveFilter(['sensor', 'camera'])
      // 场景回溯获取井下人员
    } else {
      setActiveFilter(['person', 'sensor', 'camera'])
      createSSE()
      countInterval.value = setInterval(async () => {
        const { data } = await getPersonCount()
        statistics.value = data
      }, 5000)
    }
    
  } else {
    model.value = 'realtime'
    dateRange.value = []
    authStore.setGlobalParamsItem('startTime', '')
    authStore.setGlobalParamsItem('endTime', '')
    authStore.setGlobalParamsItem('alarmId', '')
    authStore.setGlobalParamsItem('cdCode', '')
    authStore.setGlobalParamsItem('areaId', '')
    authStore.setGlobalParamsItem('areaName', '')
    authStore.setHistoryParams({
      startTime: '',
      endTime: '',
    })
    countInterval.value = setInterval(async () => {
      const { data } = await getPersonCount()
      statistics.value = data
    }, 30000)
  }
})

watch(() => globalParams.value.areaId, async (val) => {
  if (val) {
    area.value = areaList.value.find((item: any) => item.id === val)
    const { data } = await getTunnelIdByAreaId(val)
    emiter.emit('areaChange', data)
  } else {
    area.value = { id: '', label: '' }
    emiter.emit('areaChange', null)
  }
  personStore.getPersons()
})

const area = ref({ id: '', label: '' })
const areaList = ref([])
async function handleAreaChange (value: any) {
  authStore.setGlobalParamsItem('areaId', value?.id || '')
  authStore.setGlobalParamsItem('areaName', value?.label || '')
}



// 定时更新数据
const interval = ref()
const personStore = usePersonStore()
onMounted(async () => {
  try {
    alarmStore.getAlarmCount()
    personStore.getPersons()
    dictStore()
      .getAreaList()
      .then((res) => {
        areaList.value = res
      })
    const { data } = await getPersonCount()
    statistics.value = data
  } catch (error) {
    console.log(error)
  }
  interval.value = setInterval(async () => {
    alarmStore.getAlarmCount()
    personStore.getPersons()
  }, 30000)
})

onUnmounted(() => {
  clearInterval(interval.value)
})

// 告警
const alarmStore = useAlarmStore()
const { alarmCount } = storeToRefs(alarmStore)
const handleAlarm = () => {
  $bDialog({
    title: '未读告警',
    Comp: AlarmTable,
    width: 1080,
    height: 600
  })
}

const audioRef = ref()
watch(() => alarmCount.value, (val) => {
  if (val > 0) {
    audioRef.value.play()
  } else {
    audioRef.value.pause()
  }
})


const handleLogout = () => {
  // TODO: 退出登录
}
</script>
<style lang="scss" scoped>
.header {
  width: 100%;
  padding: 0 24px;

  display: flex;
  justify-content: space-between;
  align-items: center;

  .header-left {
    display: flex;
    align-items: end;

    .logo {
      height: 50px;
    }

    .logo-text {
      color: var(--text-color-disabled);
      font-size: 18px;
      padding-bottom: 6px;
      margin-left: 6px;
    }

    .statistics {
      margin-left: 32px;
      display: flex;
      align-items: center;
      padding-bottom: 6px;
      font-size: 14px;
      cursor: pointer;

      .statistics-item {
        margin-right: 24px;
        display: flex;
        align-items: center;
        justify-content: center;

        .statistics-item-title {
          color: var(--text-color);
        }

        .statistics-item-value {
          color: var(--el-color-primary);
        }
      }
    }
  }

  .header-right {
    display: flex;
    align-items: center;

    .toogle-model {
      margin-right: 20px;
    }

    .area-select {
      width: 130px;
      margin-right: 30px;

      :deep(.el-select__wrapper) {
        background: transparent !important;
        box-shadow: none !important;
        border: 1px solid var(--el-color-primary) !important;
        border-radius: 50px !important;

        & .el-select__placeholder {
          &.is-transparent {
            color: rgb(137, 184, 184) !important;
          }
        }
      }
    }

    .menu-box {
      display: flex;
      align-items: center;
      margin-left: 10px;
      margin-right: 20px;

      .menu-item {
        display: flex;
        align-items: center;
        justify-content: center;
        width: 100px;
        height: 50px;
        border-radius: 10px;
        cursor: pointer;
        letter-spacing: 1px;
        color: var(--text-color-disabled);

        &.active,
        &:hover {
          color: var(--el-color-primary);
        }

        &:not(:last-child) {
          margin-right: 10px;
        }
      }
    }

    .badge {
      margin-right: 40px;
      cursor: pointer;

      :deep(.el-badge__content--danger) {
        background-color: var(--el-color-danger-light-8);
        border-color: var(--el-color-danger-light-8);
        color: var(--el-color-danger);
      }

      .iconfont {
        font-size: 28px;

        &.danger {
          animation: dangerColor 1s infinite;
        }
      }
    }

    .login-btn {
      color: var(--text-color);
      font-size: 14px;
      padding: 4px 24px;
      background-color: var(--el-color-primary-light-5) !important;
      border-color: var(--el-color-primary-light-5) !important;
    }
  }
}

:deep(.datePicker) {
  width: 100%;
}
</style>
